<?php

require_once "../common/login.php";

$string_law = "//table[@class='laws largepadded']/tr";
$string_name = "./td[1]";
$string_vote = "./td[3]";
$string_link = "./td[1]/a";
$string_money = "//p[@class='largepadded']";

$username = "super_weapon@126.com";
$userpass = "654321";


function ParseDetail($link)
{
	global $pageCURL;
	global $string_money;
	
	$filename = "http://www.erepublik.com$link";
	do {
		$file = $pageCURL->getPage($filename);
	} while ($file === FALSE);
	
	$doc = new DOMDocument();
	$doc->loadHTML($file);
	$xpath = new DOMXpath($doc);
	
	$result = $xpath->query($string_money);
	$sentence = $result->item(1)->textContent;
	preg_match('/issue\s(\d+)\s/', $sentence, $match);

	return intval($match[1]);
}


function ParseList($country,$page)
{
	global $pageCURL;
	global $string_law, $string_name, $string_vote,$string_link;
	global $total, $content;
	
	$filename = "http://www.erepublik.com/en/$country/country-administration/$page";
	do {
		$file = $pageCURL->getPage($filename);
	} while ($file === FALSE);
	
	$doc = new DOMDocument();
	$doc->loadHTML($file);
	$xpath = new DOMXpath($doc);
	
	$laws = $xpath->query($string_law);
	
	foreach($laws as $law) {
		$name = $xpath->query($string_name, $law);
		$vote = $xpath->query($string_vote, $law);
		if ($name->length > 0) {
			 if ($name->item(0)->textContent === "Issue Money" && $vote->item(0)->textContent === "Accepted" ) {
			 	echo "accepted issue money law: ";
			 	$link = $xpath->query($string_link, $law);
			 	$url = $link->item(0)->getAttribute('href');
			 	$num = ParseDetail($url);
			 	echo $num . "\n";
				$content .= "http://www.erepublik.com$url ($num)\r\n";
			 	$total += $num;
			}
		}
	}
	
	$returncode = TRUE;
	if ( strrpos($file, "Go to next page") === FALSE ) {
		echo "\nAll pages parsed\n";
		$returncode = FALSE;
	}
	
	return $returncode;
}


// main 

if ($argc != 2) {
	die("Usage: $argv[0] country_name\n");
}

$pageCURL = new loginObj();

if ( $pageCURL->login($username, $userpass) == TRUE ) {
	echo "Login succeed.\n";
} else {
	die("Login failed.\n");
}

libxml_use_internal_errors(true);

$content = '';
$total = 0;
$i = 0;

do {
	++$i;
	echo "Parsing page $i ...\n";
	$result = ParseList($argv[1], $i);
} while ($result);

$content .= "Total: $total\r\n";

$file = fopen($argv[1] . '.txt', 'w');
fwrite($file, $content);
fclose($file);

?>
